<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="keywords" content="Hexo Theme Keep">
    <meta name="description" content="Hexo Theme Keep">
    <meta name="author" content="Tckapco">
    
    <title>
        
            ES6-Set,Map |
        
        Tckapco
    </title>
    
<link rel="stylesheet" href="/css/style.css">

    <link rel="shortcut icon" href="/images/logo.svg">
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/css/font-awesome.min.css">
    <script id="hexo-configurations">
    let KEEP = window.KEEP || {};
    KEEP.hexo_config = {"hostname":"theboat.gitee.io","root":"/","language":"en"};
    KEEP.theme_config = {"toc":{"enable":true,"number":true,"expand_all":true,"init_open":true},"style":{"primary_color":"#0066CC","avatar":"/images/avatar.jpg","favicon":"/images/logo.svg","article_img_align":"left","left_side_width":"260px","content_max_width":"920px","hover":{"shadow":false,"scale":true},"first_screen":{"enable":true,"background_img":"/images/bg.svg","description":"Keep writing and Keep loving."},"scroll":{"progress_bar":{"enable":false},"percent":{"enable":false}}},"local_search":{"enable":false,"preload":false},"code_copy":{"enable":true,"style":"mac"},"pjax":{"enable":false},"lazyload":{"enable":false},"version":"3.4.5"};
    KEEP.language_ago = {"second":"%s seconds ago","minute":"%s minutes ago","hour":"%s hours ago","day":"%s days ago","week":"%s weeks ago","month":"%s months ago","year":"%s years ago"};
  </script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
<div class="progress-bar-container">
    

    
</div>


<main class="page-container">

    

    <div class="page-main-content">

        <div class="page-main-content-top">
            <header class="header-wrapper">

    <div class="header-content">
        <div class="left">
            
            <a class="logo-title" href="/">
                Tckapco
            </a>
        </div>

        <div class="right">
            <div class="pc">
                <ul class="menu-list">
                    
                        <li class="menu-item">
                            <a class=""
                               href="/"
                            >
                                HOME
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/archives"
                            >
                                ARCHIVES
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/categories"
                            >
                                CATEGORIES
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/links"
                            >
                                LINKS
                            </a>
                        </li>
                    
                    
                </ul>
            </div>
            <div class="mobile">
                
                <div class="icon-item menu-bar">
                    <div class="menu-bar-middle"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="header-drawer">
        <ul class="drawer-menu-list">
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/">HOME</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/archives">ARCHIVES</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/categories">CATEGORIES</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/links">LINKS</a>
                </li>
            
        </ul>
    </div>

    <div class="window-mask"></div>

</header>


        </div>

        <div class="page-main-content-middle">

            <div class="main-content">

                
                    <div class="fade-in-down-animation">
    <div class="article-content-container">

        <div class="article-title">
            <span class="title-hover-animation">ES6-Set,Map</span>
        </div>

        
            <div class="article-header">
                <div class="avatar">
                    <img src="/images/avatar.jpg">
                </div>
                <div class="info">
                    <div class="author">
                        <span class="name">Tckapco</span>
                        
                            <span class="author-label">Lv2</span>
                        
                    </div>
                    <div class="meta-info">
                        <div class="article-meta-info">
    <span class="article-date article-meta-item">
        <i class="fas fa-edit"></i>&nbsp;
        <span class="pc">2021-05-20 14:03:01</span>
        <span class="mobile">2021-05-20 14:03</span>
    </span>
    
        <span class="article-categories article-meta-item">
            <i class="fas fa-folder"></i>&nbsp;
            <ul>
                
                    <li>
                        <a href="/categories/JavaScript/">JavaScript</a>&nbsp;
                    </li>
                
                    <li>
                        &gt; <a href="/categories/JavaScript/ES6/">ES6</a>&nbsp;
                    </li>
                
            </ul>
        </span>
    
    
        <span class="article-tags article-meta-item">
            <i class="fas fa-tags"></i>&nbsp;
            <ul>
                
                    <li>
                        <a href="/tags/Set-Map/">Set,Map</a>&nbsp;
                    </li>
                
            </ul>
        </span>
    

    
    
        <span class="article-wordcount article-meta-item">
            <i class="fas fa-file-word"></i>&nbsp;<span>3k Words</span>
        </span>
    
    
        <span class="article-min2read article-meta-item">
            <i class="fas fa-clock"></i>&nbsp;<span>12 Mins</span>
        </span>
    
    
</div>

                    </div>
                </div>
            </div>
        

        <div class="article-content markdown-body">
            <h1 id="一、引言"><a href="#一、引言" class="headerlink" title="一、引言"></a>一、引言</h1><p>Set和Map主要的应用场景在于<strong>数组去重</strong>和<strong>数据存储</strong></p>
<p>set = 集合   Map = 字典</p>
<h2 id="1-集合"><a href="#1-集合" class="headerlink" title="1.集合"></a>1.集合</h2><ul>
<li>集合是由一组无序且唯一(即不能重复)的项组成的，可以想象成集合是一个既没有重复元素，也没有顺序概念的数组</li>
<li>ES6提供了新的数据结构Set。它类似于数组，但是成员的值都是唯一的，没有重复的值</li>
<li>Set 本身是一个构造函数，用来生成 Set 数据结构</li>
</ul>
<h2 id="2-字典"><a href="#2-字典" class="headerlink" title="2.字典"></a>2.字典</h2><p>在数据结构还有一种结构叫做<strong>字典</strong>，它就是实现基于ES6中的Map类的结构</p>
<p>那么集合又和字典有什么区别呢：</p>
<ul>
<li>共同点：集合、字典可以存储不重复的值</li>
<li>不同点：集合是以[值，值]的形式存储元素，字典是以[键，值]的形式存储</li>
</ul>
<h1 id="二、set"><a href="#二、set" class="headerlink" title="二、set"></a>二、set</h1><h2 id="1-特点"><a href="#1-特点" class="headerlink" title="1.特点"></a>1.特点</h2><ul>
<li><p>相当于集合，集合是由一组无序且唯一(即不能重复)的项组成的，可以想象成集合是一个既没有重复元素，也没有顺序概念的数组</p>
</li>
<li><p>Set 本身是一个构造函数，用来生成 Set 数据结构</p>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">new Set([iterable])</span><br></pre></td></tr></table></figure>

<h2 id="2-基本用法"><a href="#2-基本用法" class="headerlink" title="2.基本用法"></a>2.基本用法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 例一</span><br><span class="line">const set &#x3D; new Set([1, 2, 3, 4, 4]);</span><br><span class="line">[...set]</span><br><span class="line">&#x2F;&#x2F; [1, 2, 3, 4]</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 例二</span><br><span class="line">const s &#x3D; new Set();</span><br><span class="line"></span><br><span class="line">[2, 3, 5, 4, 5, 2, 2].forEach(x &#x3D;&gt; s.add(x));</span><br><span class="line"></span><br><span class="line">for (let i of s) &#123;</span><br><span class="line">  console.log(i);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; 2 3 5 4</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 例三</span><br><span class="line">const items &#x3D; new Set([1, 2, 3, 4, 5, 5, 5, 5]);</span><br><span class="line">items.size &#x2F;&#x2F; 5</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 数组去重方法</span><br><span class="line">&#x2F;&#x2F; 一</span><br><span class="line">[...new Set(array)]</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 二</span><br><span class="line">function dedupe(array) &#123;</span><br><span class="line">  return Array.from(new Set(array));</span><br><span class="line">&#125;</span><br><span class="line">dedupe([1, 1, 2, 3]) &#x2F;&#x2F; [1, 2, 3]</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 两个对象总是不相等</span><br><span class="line">let set &#x3D; new Set();</span><br><span class="line"></span><br><span class="line">set.add(&#123;&#125;);</span><br><span class="line">set.size &#x2F;&#x2F; 1</span><br><span class="line"></span><br><span class="line">set.add(&#123;&#125;);</span><br><span class="line">set.size &#x2F;&#x2F; 2</span><br></pre></td></tr></table></figure>

<p>Set 对象允许你储存任何类型的唯一值，无论是<strong>原始值</strong>或者是<strong>对象引用</strong>。</p>
<p>向 Set 加入值的时候，不会发生类型转换，所以<code>5</code>和<code>&quot;5&quot;</code>是两个不同的值。Set 内部判断两个值是否不同，使用的算法叫做“Same-value-zero equality”，它类似于<strong>精确相等</strong>运算符（<code>===</code>），主要的区别是**<code>NaN</code>等于自身，而精确相等运算符认为<code>NaN</code>不等于自身。**</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">let set &#x3D; new Set();</span><br><span class="line">let a &#x3D; NaN;</span><br><span class="line">let b &#x3D; NaN;</span><br><span class="line">set.add(a);</span><br><span class="line">set.add(b);</span><br><span class="line">set &#x2F;&#x2F; Set &#123;NaN&#125;</span><br><span class="line"></span><br><span class="line">let set1 &#x3D; new Set()</span><br><span class="line">set1.add(5)</span><br><span class="line">set1.add(&#39;5&#39;)</span><br><span class="line">console.log([...set1])	&#x2F;&#x2F; [5, &quot;5&quot;]</span><br></pre></td></tr></table></figure>

<h2 id="3-属性方法"><a href="#3-属性方法" class="headerlink" title="3.属性方法"></a>3.属性方法</h2><p>Set 结构的实例有以下属性。</p>
<ul>
<li><code>Set.prototype.constructor</code>：构造函数，默认就是<code>Set</code>函数。</li>
<li><code>Set.prototype.size</code>：返回<code>Set</code>实例的成员总数。</li>
</ul>
<p>Set 实例的方法分为两大类：操作方法（用于操作数据）和遍历方法（用于遍历成员）。下面先介绍四个操作方法。</p>
<ul>
<li><code>Set.prototype.add(value)</code>：添加某个值，返回 Set 结构本身。</li>
<li><code>Set.prototype.delete(value)</code>：删除某个值，返回一个布尔值，表示删除是否成功。</li>
<li><code>Set.prototype.has(value)</code>：返回一个布尔值，表示该值是否为<code>Set</code>的成员。</li>
<li><code>Set.prototype.clear()</code>：清除所有成员，没有返回值。</li>
</ul>
<h2 id="4-遍历操作"><a href="#4-遍历操作" class="headerlink" title="4.遍历操作"></a>4.遍历操作</h2><p>Set 结构的实例有四个遍历方法，可以用于遍历成员。</p>
<ul>
<li><code>Set.prototype.keys()</code>：返回键名的遍历器</li>
<li><code>Set.prototype.values()</code>：返回键值的遍历器</li>
<li><code>Set.prototype.entries()</code>：返回键值对的遍历器</li>
<li><code>Set.prototype.forEach()</code>：使用回调函数遍历每个成员</li>
</ul>
<p><strong>1.keys()，values()，entries()</strong></p>
<p>三种方法都是返回遍历器对象，由于Set结构没有键名，只有键值(或者说键名跟键值是同一个值)，所以keys方法和values方法的行为完全一致。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">let set &#x3D; new Set([&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;]);</span><br><span class="line"></span><br><span class="line">for (let item of set.keys()) &#123;</span><br><span class="line">  console.log(item);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; red</span><br><span class="line">&#x2F;&#x2F; green</span><br><span class="line">&#x2F;&#x2F; blue</span><br><span class="line"></span><br><span class="line">for (let item of set.values()) &#123;</span><br><span class="line">  console.log(item);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; red</span><br><span class="line">&#x2F;&#x2F; green</span><br><span class="line">&#x2F;&#x2F; blue</span><br><span class="line"></span><br><span class="line">for (let item of set.entries()) &#123;</span><br><span class="line">  console.log(item);</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; [&quot;red&quot;, &quot;red&quot;]</span><br><span class="line">&#x2F;&#x2F; [&quot;green&quot;, &quot;green&quot;]</span><br><span class="line">&#x2F;&#x2F; [&quot;blue&quot;, &quot;blue&quot;]</span><br></pre></td></tr></table></figure>

<p><strong>Set 结构的实例默认可遍历，它的默认遍历器生成函数就是它的<code>values</code>方法。</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Set</span>.prototype[<span class="built_in">Symbol</span>.iterator] === <span class="built_in">Set</span>.prototype.values</span><br><span class="line"><span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>这意味着，可以省略<code>values</code>方法，直接用<code>for...of</code>循环遍历 Set。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> set = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="string">&#x27;red&#x27;</span>, <span class="string">&#x27;green&#x27;</span>, <span class="string">&#x27;blue&#x27;</span>]);</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> x <span class="keyword">of</span> set) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(x);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// red</span></span><br><span class="line"><span class="comment">// green</span></span><br><span class="line"><span class="comment">// blue</span></span><br></pre></td></tr></table></figure>

<p><strong>2.forEach()</strong></p>
<p>Set 结构的实例与数组一样，也拥有<code>forEach</code>方法，用于对每个成员执行某种操作，没有返回值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> set = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">4</span>, <span class="number">9</span>]);</span><br><span class="line">set.forEach(<span class="function">(<span class="params">value, key</span>) =&gt;</span> <span class="built_in">console</span>.log(key + <span class="string">&#x27; : &#x27;</span> + value))</span><br><span class="line"><span class="comment">// 1 : 1</span></span><br><span class="line"><span class="comment">// 4 : 4</span></span><br><span class="line"><span class="comment">// 9 : 9</span></span><br></pre></td></tr></table></figure>

<p>上面代码说明，<code>forEach</code>方法的参数就是一个处理函数。该函数的参数与数组的<code>forEach</code>一致，依次为键值、键名、集合本身（上例省略了该参数）。这里需要注意，Set 结构的键名就是键值（两者是同一个值），因此第一个参数与第二个参数的值永远都是一样的。</p>
<p>另外，<code>forEach</code>方法还可以有第二个参数，表示绑定处理函数内部的<code>this</code>对象。</p>
<p><strong>3.遍历的应用</strong></p>
<p>可以求并集，交集和差集</p>
<h1 id="三、WeakSet"><a href="#三、WeakSet" class="headerlink" title="三、WeakSet"></a>三、WeakSet</h1><p>WeakSet 对象允许你将<strong>弱引用对象</strong>储存在一个集合中</p>
<p>WeakSet 与 Set 的区别：</p>
<ul>
<li>WeakSet 只能储存对象引用，不能存放值，而 Set 对象都可以</li>
<li>WeakSet 对象中储存的对象值都是被弱引用的，即垃圾回收机制不考虑 WeakSet 对该对象的应用，如果没有其他的变量或属性引用这个对象值，则这个对象将会被垃圾回收掉（不考虑该对象还存在于 WeakSet 中），所以，WeakSet 对象里有多少个成员元素，取决于垃圾回收机制有没有运行，运行前后成员个数可能不一致，遍历结束之后，有的成员可能取不到了（被垃圾回收了），WeakSet 对象是无法被遍历的（ES6 规定 WeakSet 不可遍历），也没有办法拿到它包含的所有元素</li>
</ul>
<p>属性：</p>
<ul>
<li><p>constructor：构造函数，任何一个具有 Iterable 接口的对象，都可以作参数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [[<span class="number">1</span>, <span class="number">2</span>], [<span class="number">3</span>, <span class="number">4</span>]]</span><br><span class="line"><span class="keyword">const</span> weakset = <span class="keyword">new</span> <span class="built_in">WeakSet</span>(arr)</span><br><span class="line"><span class="built_in">console</span>.log(weakset)</span><br></pre></td></tr></table></figure></li>
</ul>
<p><img src="https://user-images.githubusercontent.com/19721451/54000884-27290900-4184-11e9-92f0-4d19ac6d080b.png" alt="img"></p>
<p>方法：</p>
<ul>
<li>add(value)：在WeakSet 对象中添加一个元素value</li>
<li>has(value)：判断 WeakSet 对象中是否包含value</li>
<li>delete(value)：删除元素 value</li>
<li>clear()：清空所有元素，<strong>注意该方法已废弃</strong></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> ws = <span class="keyword">new</span> <span class="built_in">WeakSet</span>()</span><br><span class="line"><span class="keyword">var</span> obj = &#123;&#125;</span><br><span class="line"><span class="keyword">var</span> foo = &#123;&#125;</span><br><span class="line"></span><br><span class="line">ws.add(<span class="built_in">window</span>)</span><br><span class="line">ws.add(obj)</span><br><span class="line"></span><br><span class="line">ws.has(<span class="built_in">window</span>)	<span class="comment">// true</span></span><br><span class="line">ws.has(foo)	<span class="comment">// false</span></span><br><span class="line"></span><br><span class="line">ws.delete(<span class="built_in">window</span>)	<span class="comment">// true</span></span><br><span class="line">ws.has(<span class="built_in">window</span>)	<span class="comment">// false</span></span><br></pre></td></tr></table></figure>

<h1 id="四、Map"><a href="#四、Map" class="headerlink" title="四、Map"></a>四、Map</h1><h2 id="1-特点-1"><a href="#1-特点-1" class="headerlink" title="1.特点"></a>1.特点</h2><p>集合 与 字典 的区别：</p>
<ul>
<li>共同点：集合、字典 可以储存不重复的值</li>
<li>不同点：集合 是以 [value, value]的形式储存元素，字典 是以 [key, value] 的形式储存</li>
</ul>
<h2 id="2-基本用法-1"><a href="#2-基本用法-1" class="headerlink" title="2.基本用法"></a>2.基本用法</h2><p>Object 结构提供了“字符串—值”的对应，Map 结构提供了“值—值”的对应，是一种更完善的 Hash 结构实现。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> m = <span class="keyword">new</span> <span class="built_in">Map</span>()</span><br><span class="line"><span class="keyword">const</span> o = &#123;<span class="attr">p</span>: <span class="string">&#x27;haha&#x27;</span>&#125;</span><br><span class="line">m.set(o, <span class="string">&#x27;content&#x27;</span>)</span><br><span class="line">m.get(o)	<span class="comment">// content</span></span><br><span class="line"></span><br><span class="line">m.has(o)	<span class="comment">// true</span></span><br><span class="line">m.delete(o)	<span class="comment">// true</span></span><br><span class="line">m.has(o)	<span class="comment">// false</span></span><br></pre></td></tr></table></figure>

<p><strong>任何具有 Iterator 接口、且每个成员都是一个双元素的数组的数据结构</strong>都可以当作<code>Map</code>构造函数的参数，例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> set = <span class="keyword">new</span> <span class="built_in">Set</span>([</span><br><span class="line">  [<span class="string">&#x27;foo&#x27;</span>, <span class="number">1</span>],</span><br><span class="line">  [<span class="string">&#x27;bar&#x27;</span>, <span class="number">2</span>]</span><br><span class="line">]);</span><br><span class="line"><span class="keyword">const</span> m1 = <span class="keyword">new</span> <span class="built_in">Map</span>(set);</span><br><span class="line">m1.get(<span class="string">&#x27;foo&#x27;</span>) <span class="comment">// 1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> m2 = <span class="keyword">new</span> <span class="built_in">Map</span>([[<span class="string">&#x27;baz&#x27;</span>, <span class="number">3</span>]]);</span><br><span class="line"><span class="keyword">const</span> m3 = <span class="keyword">new</span> <span class="built_in">Map</span>(m2);</span><br><span class="line">m3.get(<span class="string">&#x27;baz&#x27;</span>) <span class="comment">// 3</span></span><br></pre></td></tr></table></figure>

<p>如果读取一个未知的键，则返回<code>undefined</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Map</span>().get(<span class="string">&#x27;asfddfsasadf&#x27;</span>)</span><br><span class="line"><span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>

<p>注意，只有对同一个对象的引用，Map 结构才将其视为同一个键。这一点要非常小心。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line"></span><br><span class="line">map.set([<span class="string">&#x27;a&#x27;</span>], <span class="number">555</span>);</span><br><span class="line">map.get([<span class="string">&#x27;a&#x27;</span>]) <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>

<p>上面代码的<code>set</code>和<code>get</code>方法，表面是针对同一个键，但实际上这是两个值，内存地址是不一样的，因此<code>get</code>方法无法读取该键，返回<code>undefined</code>。</p>
<p>由上可知，Map 的键实际上是跟内存地址绑定的，只要内存地址不一样，就视为两个键。这就解决了同名属性碰撞（clash）的问题，我们扩展别人的库的时候，如果使用对象作为键名，就不用担心自己的属性与原作者的属性同名。</p>
<p>如果 Map 的键是一个简单类型的值（数字、字符串、布尔值），则只要两个值严格相等，Map 将其视为一个键，比如<code>0</code>和<code>-0</code>就是一个键，布尔值<code>true</code>和字符串<code>true</code>则是两个不同的键。另外，<code>undefined</code>和<code>null</code>也是两个不同的键。虽然<code>NaN</code>不严格相等于自身，但 Map 将其视为同一个键。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line"></span><br><span class="line">map.set(-<span class="number">0</span>, <span class="number">123</span>);</span><br><span class="line">map.get(+<span class="number">0</span>) <span class="comment">// 123</span></span><br><span class="line"></span><br><span class="line">map.set(<span class="literal">true</span>, <span class="number">1</span>);</span><br><span class="line">map.set(<span class="string">&#x27;true&#x27;</span>, <span class="number">2</span>);</span><br><span class="line">map.get(<span class="literal">true</span>) <span class="comment">// 1</span></span><br><span class="line"></span><br><span class="line">map.set(<span class="literal">undefined</span>, <span class="number">3</span>);</span><br><span class="line">map.set(<span class="literal">null</span>, <span class="number">4</span>);</span><br><span class="line">map.get(<span class="literal">undefined</span>) <span class="comment">// 3</span></span><br><span class="line"></span><br><span class="line">map.set(<span class="literal">NaN</span>, <span class="number">123</span>);</span><br><span class="line">map.get(<span class="literal">NaN</span>) <span class="comment">// 123</span></span><br></pre></td></tr></table></figure>

<h2 id="3-属性方法-1"><a href="#3-属性方法-1" class="headerlink" title="3.属性方法"></a>3.属性方法</h2><p>属性：</p>
<ul>
<li>size：返回字典所包含的元素个数</li>
</ul>
<p>操作方法：</p>
<ul>
<li>set(key, val): 向字典中添加新元素</li>
<li>get(key):通过键值查找特定的数值并返回</li>
<li>has(key):如果键存在字典中返回true,否则false</li>
<li>delete(key): 通过键值从字典中移除对应的数据</li>
<li>clear():将这个字典中的所有元素删除</li>
</ul>
<h2 id="4-遍历操作-1"><a href="#4-遍历操作-1" class="headerlink" title="4.遍历操作"></a>4.遍历操作</h2><p>Map 结构原生提供三个遍历器生成函数和一个遍历方法。</p>
<ul>
<li><code>Map.prototype.keys()</code>：返回键名的遍历器。</li>
<li><code>Map.prototype.values()</code>：返回键值的遍历器。</li>
<li><code>Map.prototype.entries()</code>：返回所有成员的遍历器。</li>
<li><code>Map.prototype.forEach()</code>：遍历 Map 的所有成员。</li>
</ul>
<h2 id="5-与其他数据结构转换"><a href="#5-与其他数据结构转换" class="headerlink" title="5.与其他数据结构转换"></a>5.与其他数据结构转换</h2><p>Map转为数组</p>
<p>数组转为Map</p>
<p>Map转为对象</p>
<p>对象转为Map</p>
<p>Map转为JSON</p>
<p>JSON转为Map</p>
<h1 id="五、WeakMap"><a href="#五、WeakMap" class="headerlink" title="五、WeakMap"></a>五、WeakMap</h1><p>WeakMap 对象是一组键值对的集合，其中的<strong>键是弱引用对象，而值可以是任意</strong>。</p>
<p><strong>注意，WeakMap 弱引用的只是键名，而不是键值。键值依然是正常引用。</strong></p>
<p>WeakMap 中，每个键对自己所引用对象的引用都是弱引用，在没有其他引用和该键引用同一对象，这个对象将会被垃圾回收（相应的key则变成无效的），所以，WeakMap 的 key 是不可枚举的。</p>
<p>属性：</p>
<ul>
<li>constructor：构造函数</li>
</ul>
<p>方法：</p>
<ul>
<li>has(key)：判断是否有 key 关联对象</li>
<li>get(key)：返回key关联对象（没有则则返回 undefined）</li>
<li>set(key)：设置一组key关联对象</li>
<li>delete(key)：移除 key 的关联对象</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> myElement = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;logo&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> myWeakmap = <span class="keyword">new</span> <span class="built_in">WeakMap</span>();</span><br><span class="line"></span><br><span class="line">myWeakmap.set(myElement, &#123;<span class="attr">timesClicked</span>: <span class="number">0</span>&#125;);</span><br><span class="line"></span><br><span class="line">myElement.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> logoData = myWeakmap.get(myElement);</span><br><span class="line">  logoData.timesClicked++;</span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>

<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><ul>
<li>Set<ul>
<li>成员唯一、无序且不重复</li>
<li>[value, value]，键值与键名是一致的（或者说只有键值，没有键名）</li>
<li>可以遍历，方法有：add、delete、has</li>
</ul>
</li>
<li>WeakSet<ul>
<li>成员都是对象</li>
<li>成员都是弱引用，可以被垃圾回收机制回收，可以用来保存DOM节点，不容易造成内存泄漏</li>
<li>不能遍历，方法有add、delete、has</li>
</ul>
</li>
<li>Map<ul>
<li>本质上是键值对的集合，类似集合</li>
<li>可以遍历，方法很多可以跟各种数据格式转换</li>
</ul>
</li>
<li>WeakMap<ul>
<li>只接受对象作为键名（null除外），不接受其他类型的值作为键名</li>
<li>键名是弱引用，键值可以是任意的，键名所指向的对象可以被垃圾回收，此时键名是无效的</li>
<li>不能遍历，方法有get、set、has、delete</li>
</ul>
</li>
</ul>
<h1 id="个人总结"><a href="#个人总结" class="headerlink" title="个人总结"></a>个人总结</h1><p>Set、Map都是ES6新型的数据结构，Set相当于集合，特点是无序且唯一，可以理解为无序且唯一的数组。Map相当于字典，为“值 - 值”对应。这两者都可以遍历，方法相似</p>
<p>而WeakSet，WeakMap成员都是弱引用，可以被垃圾回收，这两者不能被遍历。</p>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><p>阮一峰：<a target="_blank" rel="noopener" href="https://es6.ruanyifeng.com/#docs/set-map">https://es6.ruanyifeng.com/#docs/set-map</a></p>
<p>ES6的Set和Map数据结构，由你制造：<a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903589920374792">https://juejin.cn/post/6844903589920374792</a></p>
<p>木易杨前端进阶：<a target="_blank" rel="noopener" href="https://muyiy.cn/question/js/4.html">https://muyiy.cn/question/js/4.html</a></p>

        </div>

        

        
            <ul class="post-tags-box">
                
                    <li class="tag-item">
                        <a href="/tags/Set-Map/">#Set,Map</a>&nbsp;
                    </li>
                
            </ul>
        

        
            <div class="article-nav">
                
                    <div class="article-prev">
                        <a class="prev"
                           rel="prev"
                           href="/2021/05/27/%E7%BD%91%E7%BB%9C%E5%AE%89%E5%85%A8-XSS,CSRF/"
                        >
                            <span class="left arrow-icon flex-center">
                              <i class="fas fa-chevron-left"></i>
                            </span>
                            <span class="title flex-center">
                                <span class="post-nav-title-item">网络安全-XSS,CSRF</span>
                                <span class="post-nav-item">Prev posts</span>
                            </span>
                        </a>
                    </div>
                
                
                    <div class="article-next">
                        <a class="next"
                           rel="next"
                           href="/2021/05/17/%E5%BC%82%E6%AD%A5%E6%96%B9%E6%A1%88%E2%80%94%E2%80%94Generator/"
                        >
                            <span class="title flex-center">
                                <span class="post-nav-title-item">异步方案——Generator</span>
                                <span class="post-nav-item">Next posts</span>
                            </span>
                            <span class="right arrow-icon flex-center">
                              <i class="fas fa-chevron-right"></i>
                            </span>
                        </a>
                    </div>
                
            </div>
        

        
    </div>
</div>


                
            </div>

        </div>

        <div class="page-main-content-bottom">
            <footer class="footer">
    <div class="info-container">
        <div class="copyright-info info-item">
            &copy;
            
              <span>2020</span>
              -
            
            2022&nbsp;<i class="fas fa-heart icon-animate"></i>&nbsp;<a href="/">Tckapco</a>
        </div>
        
        <div class="theme-info info-item">
            Powered by <a target="_blank" href="https://hexo.io">Hexo</a>&nbsp;|&nbsp;Theme&nbsp;<a class="theme-version" target="_blank" href="https://github.com/XPoet/hexo-theme-keep">Keep v3.4.5</a>
        </div>
        
        
    </div>
</footer>

        </div>
    </div>

    
        <div class="post-tools">
            <div class="post-tools-container">
    <ul class="tools-list">
        <!-- TOC aside toggle -->
        
            <li class="tools-item page-aside-toggle">
                <i class="fas fa-outdent"></i>
            </li>
        

        <!-- go comment -->
        
    </ul>
</div>

        </div>
    

    <div class="right-bottom-side-tools">
        <div class="side-tools-container">
    <ul class="side-tools-list">
        <li class="tools-item tool-font-adjust-plus flex-center">
            <i class="fas fa-search-plus"></i>
        </li>

        <li class="tools-item tool-font-adjust-minus flex-center">
            <i class="fas fa-search-minus"></i>
        </li>

        <li class="tools-item tool-expand-width flex-center">
            <i class="fas fa-arrows-alt-h"></i>
        </li>

        <li class="tools-item tool-dark-light-toggle flex-center">
            <i class="fas fa-moon"></i>
        </li>

        <!-- rss -->
        

        
            <li class="tools-item tool-scroll-to-top flex-center">
                <i class="fas fa-arrow-up"></i>
            </li>
        

        <li class="tools-item tool-scroll-to-bottom flex-center">
            <i class="fas fa-arrow-down"></i>
        </li>
    </ul>

    <ul class="exposed-tools-list">
        <li class="tools-item tool-toggle-show flex-center">
            <i class="fas fa-cog fa-spin"></i>
        </li>
        
    </ul>
</div>

    </div>

    
        <aside class="page-aside">
            <div class="post-toc-wrap">
    <div class="post-toc">
        <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E5%BC%95%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">一、引言</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E9%9B%86%E5%90%88"><span class="nav-number">1.1.</span> <span class="nav-text">1.集合</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%AD%97%E5%85%B8"><span class="nav-number">1.2.</span> <span class="nav-text">2.字典</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81set"><span class="nav-number">2.</span> <span class="nav-text">二、set</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E7%89%B9%E7%82%B9"><span class="nav-number">2.1.</span> <span class="nav-text">1.特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95"><span class="nav-number">2.2.</span> <span class="nav-text">2.基本用法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%B1%9E%E6%80%A7%E6%96%B9%E6%B3%95"><span class="nav-number">2.3.</span> <span class="nav-text">3.属性方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E9%81%8D%E5%8E%86%E6%93%8D%E4%BD%9C"><span class="nav-number">2.4.</span> <span class="nav-text">4.遍历操作</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81WeakSet"><span class="nav-number">3.</span> <span class="nav-text">三、WeakSet</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9B%E3%80%81Map"><span class="nav-number">4.</span> <span class="nav-text">四、Map</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E7%89%B9%E7%82%B9-1"><span class="nav-number">4.1.</span> <span class="nav-text">1.特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95-1"><span class="nav-number">4.2.</span> <span class="nav-text">2.基本用法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%B1%9E%E6%80%A7%E6%96%B9%E6%B3%95-1"><span class="nav-number">4.3.</span> <span class="nav-text">3.属性方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E9%81%8D%E5%8E%86%E6%93%8D%E4%BD%9C-1"><span class="nav-number">4.4.</span> <span class="nav-text">4.遍历操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E4%B8%8E%E5%85%B6%E4%BB%96%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E8%BD%AC%E6%8D%A2"><span class="nav-number">4.5.</span> <span class="nav-text">5.与其他数据结构转换</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%94%E3%80%81WeakMap"><span class="nav-number">5.</span> <span class="nav-text">五、WeakMap</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%AA%E4%BA%BA%E6%80%BB%E7%BB%93"><span class="nav-number">7.</span> <span class="nav-text">个人总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number">8.</span> <span class="nav-text">参考</span></a></li></ol>
    </div>
</div>
        </aside>
    

    <div class="image-viewer-container">
    <img src="">
</div>


    

</main>



<script src="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/js/utils.js"></script><script src="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/js/main.js"></script><script src="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/js/header-shrink.js"></script><script src="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/js/back2top.js"></script><script src="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/js/dark-light-toggle.js"></script>




    <script src="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/js/code-copy.js"></script>




<div class="post-scripts">
    
        <script src="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/js/left-side-toggle.js"></script><script src="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/js/libs/anime.min.js"></script><script src="//cdn.jsdelivr.net/npm/hexo-theme-keep@3.4.5/source/js/toc.js"></script>
    
</div>



</body>
</html>
